package io.renren.modules.generator.service.impl;

import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.MessageDao;
import io.renren.modules.generator.entity.MessageEntity;
import io.renren.modules.generator.service.MessageService;


@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MessageEntity> page = this.page(
                new Query<MessageEntity>().getPage(params),
                new QueryWrapper<MessageEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveMessage(MessageEntity message) {
        //获取发送者id
        Long sendId = ShiroUtils.getUserId();
        Long receiveId = message.getReceiveId();
        //获取发送者名称
        String sendName = sysUserService.getById(sendId).getUsername();
        //获取接收者姓名
        String receiveName = sysUserService.getById(receiveId).getUsername();
        message.setSendId(sendId);
        message.setSendName(sendName);
        message.setReceiveName(receiveName);
        //获取当前发送消息时间
        message.setSendTime(new Date());
        baseMapper.insert(message);

    }

    @Override
    public List<MessageEntity> getMessList(Long friendId) {
        Long userId = ShiroUtils.getUserId();
        //查询当前用户好友是friendId的所有聊天记录-并通过消息发送时间倒叙排序
        List<MessageEntity> list = this.lambdaQuery().and(wq -> wq.eq(MessageEntity::getSendId, userId).eq(MessageEntity::getReceiveId, friendId))
                .or(wq -> wq.eq(MessageEntity::getSendId, friendId).eq(MessageEntity::getReceiveId, userId))
                .orderByDesc(MessageEntity::getSendTime).list();
        return list;
    }

}
